package com.tanchengjin.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tanchengjin.admin.model.dao.AdminRoleMapper;
import com.tanchengjin.admin.model.dao.AdminRolePermissionMapper;
import com.tanchengjin.admin.model.pojo.AdminRole;
import com.tanchengjin.admin.model.pojo.AdminUserRole;
import com.tanchengjin.admin.service.AdminRoleService;
import com.tanchengjin.admin.service.AdminUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author TanChengjin
 * @version v1.0.0
 * @email 18865477815@163.com
 */
@Service("AdminRoleService")
public class AdminRoleServiceImpl extends ServiceImpl<AdminRoleMapper, AdminRole> implements AdminRoleService {
    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @Autowired
    private AdminRolePermissionMapper adminRolePermissionMapper;
    @Autowired
    private AdminUserRoleService adminUserRoleService;

    @Override
    @Transactional
    public int update(AdminRole adminRole) {
        adminRoleMapper.updateByPrimaryKeySelective(adminRole);
        //清空角色权限，重新分配角色权限
        adminRolePermissionMapper.flushAllByRoleId(adminRole.getId());
        return 0;
    }

    @Override
    public List<Integer> getIdsBySysUserId(int userid) {
        List<AdminUserRole> rolesBySysUserId = getRolesBySysUserId(userid);
        return rolesBySysUserId.stream().map(AdminUserRole::getAdminRoleId).collect(Collectors.toList());
    }

    @Override
    public List<AdminUserRole> getRolesBySysUserId(int userid) {
        QueryWrapper<AdminUserRole> adminUserRoleQueryWrapper = new QueryWrapper<>();
        adminUserRoleQueryWrapper.eq("admin_user_id", userid);
        List<AdminUserRole> list = adminUserRoleService.list(adminUserRoleQueryWrapper);
        return list;
    }
}
